import requests
from bs4 import BeautifulSoup
from urllib.request import urlretrieve

def getImage():
    headers = {
        'User-Agent' : 'Mozilla / 5.0(Windows NT 10.0; Win64; x64; rv: 88.0) Gecko / 20100101 Firefox / 88.0'
    }

    url = 'https://www.xxxx.com/topic/1979759'
    resource = requests.get(url,headers=headers)

    html = resource.text
    soup = BeautifulSoup(html, 'html.parser')
    images = soup.find_all('img')

    for img in images:
        name = img.get('title')
        imgUrl = img.get('src')
        # print(imgUrl)
        # path = '爬取的图片/{}.jpg'.format(name)
        #
        # urlretrieve(imgUrl,path)

        root = "爬取的图片/" # 设置保存路径
        read = requests.get(imgUrl) # 下载图片
        # print(imgUrl.split('/')[-1])
        path = root + imgUrl.split('/')[-1]
        #
        with open(path, "wb")as f:
            f.write(read.content)
            f.close()
            print("文件保存成功！")

getImage()